package middleware

import (
	"frontend-server/util"
	"net/http"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

var skipPaths = []string{"/api/v1/manage/admin/login"}

func JWTAuthMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 跳过路由鉴权
		for _, path := range skipPaths {
			if path == ctx.FullPath() {
				ctx.Next()
				return
			}
		}
		// 获取 token
		tokenString := ctx.Request.Header.Get("Authorization")
		// token 不存在
		if tokenString == "" {
			util.Success(ctx, util.R{
				P: util.P{
					Code:    http.StatusUnauthorized,
					Message: "没有权限",
				},
			})
			ctx.Abort()
			return
		}
		// token 格式错误
		tokenSlice := strings.SplitN(tokenString, " ", 2)
		if len(tokenSlice) != 2 && tokenSlice[0] != "Bearer" {
			util.Success(ctx, util.R{
				P: util.P{
					Code:    http.StatusUnauthorized,
					Message: "没有权限",
				},
			})
			ctx.Abort()
			return
		}
		// 验证 Token
		ujc, b := util.VerifyToken(tokenSlice[1])
		if !b {
			util.Success(ctx, util.R{
				P: util.P{
					Code:    http.StatusUnauthorized,
					Message: "没有权限",
				},
			})
			ctx.Abort()
			return
		}
		// token超时
		if time.Now().Unix() > ujc.ExpiresAt {
			util.Success(ctx, util.R{
				P: util.P{
					Code:    -1,
					Message: "token 过期",
				},
			})
			ctx.Abort()
			return
		}
		ctx.Set("id", ujc.ID)
		ctx.Set("username", ujc.Username)
		ctx.Next()
	}
}
